package com._101aiot.auth.service.impl;

import cn.hutool.core.collection.CollUtil;
import com._101aiot.auth.api.UserDTO;
import com._101aiot.auth.entity.SecurityUser;
import com._101aiot.common.constant.MessageConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 实现security 的 UserDetailsService， 自定义登录方法
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    ClientDetailsService clientDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    /* *********************  改造从数据库获取账户 **************************/
    // 构造用户信息
    private List<UserDTO> userList;

    // 构造用户名密码
    @PostConstruct
    public void initData() {

        String password = passwordEncoder.encode("123456");
        userList = new ArrayList<>();
        userList.add(new UserDTO(1L, "admin", password, 1, CollUtil.toList("admin")));
        userList.add(new UserDTO(2L, "test", password, 1, CollUtil.toList("test")));
        userList.add(new UserDTO(3L, "a1", password, 1, CollUtil.toList("test")));
        userList.add(new UserDTO(4L, "a2", password, 1, CollUtil.toList("test")));

    }

    /* *********************   **************************/


    /**
     * @param username 用户名，前端传入
     * @return UserDetails 对象
     * @throws UsernameNotFoundException 抛出用户名未找到异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) {

        // Oauth2ServerConfig 这个配置已经请求了数据库并校验了
        //取出身份，如果身份为空说明没有认证
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
//
//        // 没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
//        if(authentication==null){
//            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(username);
//            if(clientDetails!=null){
//                //密码
//                String clientSecret = clientDetails.getClientSecret();
//                return new User(username,clientSecret, AuthorityUtils.commaSeparatedStringToAuthorityList(""));
//            }
//        }
//        if (StrUtil.isEmpty(username)) {
//            return null;
//        }

        // 判断登录的 逻辑
        List<UserDTO> findUserList = userList.stream().filter(item -> item.getUsername().equals(username)).collect(Collectors.toList());
        if (CollUtil.isEmpty(findUserList)) {
            // 用户名或密码错误
//            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
            return null;
        }


        // TODO 这边处理各种账号不存在，抛出异常即可
        // 密码自动校验，自动抛出异常
        // 这里抛出权限
        // 账号锁定
        // 账户停用
        // 账户过期
        // == ==


        // 校验密码是否正确

        // 校验权限

        // 此处校验各种权限

        SecurityUser securityUser = new SecurityUser(findUserList.get(0));

        if (!securityUser.isEnabled()) {

            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {

            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {

            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {

            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }

}
